package rs.etf.kdp.server;

import java.util.ArrayList;
import java.util.List;

/**
 * List of available nodes
 * @author Djordje Vukovic
 * @version 1.0
 * @created 20-May-2011 2:30:18 AM
 */
public class AvailableNodes {

	//private List<Node> availableClients;
	private List<Node> availableWorkstations;

	public AvailableNodes(){
		//availableClients = new LinkedList<Node>();
		availableWorkstations = new ArrayList<Node>();
	}

	public void insertNode(Node node)
	{
		//if(node.isClient())
		//{
			//availableClients.add(node);
		//}
		//else if (node.isWorkstation())
		//{
			availableWorkstations.add(node);
		//}
	}
	
	public void removeNode(Node node)
	{
		//if(node.isClient())
		//{
			//availableClients.remove(node);
		//}
		//else if(node.isWorkstation())
		//{
			availableWorkstations.remove(node);
		//}
	}
	
	public void removeByIP(String ip)
	{
		int size = availableWorkstations.size();
		for(int i=0; i< size; i++)
		{
			if(availableWorkstations.get(i).getIpAddress().equals(ip))
			{
				availableWorkstations.remove(i);
				return;
			}
		}
	}
	
	public void removeByWorkstationName(String name)
	{
		int size = availableWorkstations.size();
		for(int i = 0; i < size; i++)
		{
			if(availableWorkstations.get(i).getNameOfNode().equals(name))
			{
				availableWorkstations.remove(i);
				return;
			}
		}
	}

	public List<Node> getAvailableWorkstations() {
		return availableWorkstations;
	}
	
	public List<Node> getFreeWorkstations(int numberOfRequired)
	{
		int size = availableWorkstations.size();
		//if(numberOfRequired > size) return null;
		//List<Node> ret = availableWorkstations.subList(0, numberOfRequired);
		List<Node> ret = new ArrayList<Node>();
		int cnt = 0;
		
		while(cnt < numberOfRequired && cnt < size)
		{
			Node current = availableWorkstations.get(cnt);
			if(current.getCurrentlyRunningThreads() < current.getPossibleThreads())
			{
				ret.add(current);
			}
				
			cnt++;
		}
		return ret; // it is possible to return less than required number
	}
	
	public boolean checkName(String name)
	{
		for(Node i : availableWorkstations)
		{
			if(name.equals(i.getNameOfNode())) return false;
		}
		return true;
	}
	
	
	public Node getNodeByIp(String ip)
	{
		int size = availableWorkstations.size();
		
		for(int i=0 ; i<size; i++)
		{
			if(availableWorkstations.get(i).getIpAddress().equals(ip))
			{
				return availableWorkstations.get(i);
			}
		}
		
		return null;
	}
	

}